package com.shk.aop;


import com.alibaba.dubbo.config.annotation.Reference;
import com.shk.ipget.IPSeeker;
import com.shk.pojo.Log4j2Db;
import com.shk.service.Log4jService;
import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class Aop001Log4j {
    @Autowired
    private HttpServletRequest request;
    @Reference
    private Log4jService log4jService;
    /**
     * 定义切入点
     */
    @Pointcut("@annotation(com.shk.annotation.Log4jAnnotation)")
    public void pc(){}

    // 配置通知类型
    @Around("pc()")
    public Object log4UserMessage2Database(ProceedingJoinPoint pjp)  {
        IPSeeker seeker = IPSeeker.getInstance();
        Log4j2Db log4j = new Log4j2Db();
        // 前置处理
        long start = System.currentTimeMillis();
        // 获得用户信息
        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = principal.getUsername();
        log4j.setUserName(username);
        Date date = new Date();
        log4j.setOpDate(date);
        // 获取操作人的ip地址
        String ip = getRequestIp();


        if(ip.equals("0:0:0:0:0:0:0:1")){
            ip="192.168.14.30";
        }
        String address = seeker.getAddress(ip);
        if(ip.equals("192.168.14.30")){
            address="本地IP";
        }
        log4j.setIP(ip);
        // 获取请求路径
        StringBuffer requestURL = request.getRequestURL();
        String[] split = requestURL.toString().split("/");

        String url1=split[split.length-2];
        String url2=split[split.length-1];
         log4j.setUrl(url1+"/"+url2);

        // 执行原始方法


        Object proceed = null;
        try {
            proceed = pjp.proceed();
        } catch (Throwable throwable) {
            long exceptionEnd = System.currentTimeMillis();
            log4j.setOpTime(exceptionEnd-start);
            // 存入到数据库
            throwable.printStackTrace();

            log4j.setCity(address);
            log4jService.addLog2Db(log4j);
            throwable.printStackTrace();
        }


        log4j.setCity(address);
        long end = System.currentTimeMillis();
        log4j.setOpTime(end-start);
        System.out.println(log4j);
        // 存入到数据库
        Object[] args = pjp.getArgs();
        System.out.println(Arrays.toString(args));
        // 返回值
        log4jService.addLog2Db(log4j);
        return proceed;

    }

    public String getRequestIp(){
        /**
         * 获取距离服务器最远的那个ip
         */
        String ip = request.getHeader("x-forwarded-for");
        if (ipIsNullOrEmpty(ip)){
            /**
             * apache http服务代理加上的ip
             */
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ipIsNullOrEmpty(ip)){
            /**
             * weblogic插件加上的头
             */
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipIsNullOrEmpty(ip)){
            /**
             * 真实ip
             */
            ip = request.getHeader("X-Real-IP");
        }
        if (ipIsNullOrEmpty(ip)){
            /**
             * 最后真实的ip
             */
            ip = request.getRemoteAddr();
        }

        return ip;
    }
    /**
     * 当前ip是否为空
     * @param ip
     * @return
     */
    public boolean ipIsNullOrEmpty(String ip){
        if(ip == null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
            return true;
        }
        return false;
    }

}
